<template>
  <div class="theme-switcher">
    <ElButton
      icon="Refresh"
      size="small"
      circle
      class="theme-button"
      @click="showDrawer"
    />

    <ElDrawer
      v-model="isVisible"
      :title="$t('systemSettings.drawerTitle')"
      :direction="direction"
    >
      <div class="theme-content">
        <ElCard>
          <template #header>
            <div class="card-header">
              <ElText
                type="primary"
                class="theme-settings-title"
                >{{ $t('systemSettings.themeSettingsTitle') }}</ElText
              >
            </div>
          </template>

          <ElRow>
            <ElCol :span="6">
              <!-- 主色调设置 -->
              <div class="theme-item">
                <ElText type="primary">{{ $t('themeSettings.primaryColor') }}</ElText>
                <ElColorPicker
                  v-model="primaryColor"
                  :predefine="predefinedColors"
                  @change="handlePrimaryColorChange"
                  class="color-picker"
                />
              </div>
            </ElCol>

            <ElCol :span="6">
              <!-- 辅助色调设置 -->
              <div class="theme-item">
                <ElText type="primary">{{ $t('themeSettings.successColor') }}</ElText>
                <ElColorPicker
                  v-model="successColor"
                  :predefine="predefinedColors"
                  @change="handleSuccessColorChange"
                  class="color-picker"
                />
              </div>
            </ElCol>

            <ElCol :span="6">
              <div class="theme-item">
                <ElText type="primary">{{ $t('themeSettings.warningColor') }}</ElText>
                <ElColorPicker
                  v-model="warningColor"
                  :predefine="predefinedColors"
                  @change="handleWarningColorChange"
                  class="color-picker"
                />
              </div>
            </ElCol>

            <ElCol :span="6">
              <div class="theme-item">
                <ElText type="primary">{{ $t('themeSettings.dangerColor') }}</ElText>
                <ElColorPicker
                  v-model="dangerColor"
                  :predefine="predefinedColors"
                  @change="handleDangerColorChange"
                  class="color-picker"
                />
              </div>
            </ElCol>
          </ElRow>

          <template #footer>
            <!-- 重置按钮 -->
            <ElButton
              size="small"
              link
              @click="resetTheme"
              type="primary"
            >
              {{ $t('themeSettings.resetTheme') }}
            </ElButton>
            <DarkMode style="margin-left: 10px" />
          </template>
        </ElCard>
      </div>
    </ElDrawer>
  </div>
</template>

<script setup lang="ts">
  const isVisible = ref<boolean>(false)
  const direction = ref<'rtl' | 'ltr' | 'ttb' | 'btt'>('rtl')

  // 主题颜色类型定义
  interface ThemeColors {
    primary: string
    success: string
    warning: string
    danger: string
  }

  // 默认主题色（Element Plus 官方默认）
  const defaultTheme: ThemeColors = {
    primary: '#409eff',
    success: '#67c23a',
    warning: '#e6a23c',
    danger: '#f56c6c',
  }

  // 预定义颜色选项
  const predefinedColors = [
    '#409eff',
    '#67c23a',
    '#e6a23c',
    '#f56c6c',
    '#909399',
    '#1890ff',
    '#00b42a',
    '#ff7d00',
    '#f53f3f',
    '#722ed1',
    '#fa541c',
    '#13c2c2',
  ]

  // 响应式主题色变量
  const primaryColor = ref<string>(defaultTheme.primary)
  const successColor = ref<string>(defaultTheme.success)
  const warningColor = ref<string>(defaultTheme.warning)
  const dangerColor = ref<string>(defaultTheme.danger)

  const showDrawer = () => {
    isVisible.value = true
  }

  const hideDrawer = () => {
    isVisible.value = false
  }

  // 初始化主题（从本地存储加载）
  const initTheme = () => {
    const savedTheme = localStorage.getItem('app-theme')
    if (savedTheme) {
      try {
        const parsedTheme = JSON.parse(savedTheme) as ThemeColors
        primaryColor.value = parsedTheme.primary
        successColor.value = parsedTheme.success
        warningColor.value = parsedTheme.warning
        dangerColor.value = parsedTheme.danger

        // 应用保存的主题
        applyTheme(parsedTheme)
      } catch (error) {
        console.error('加载保存的主题失败', error)
        localStorage.removeItem('app-theme')
      }
    }
  }

  // 应用主题到页面
  const applyTheme = (theme: Partial<ThemeColors>) => {
    const style = document.documentElement.style

    // 设置 CSS 变量
    if (theme.primary) {
      style.setProperty('--el-color-primary', theme.primary)
      style.setProperty('--el-color-primary-light-3', lighten(theme.primary, 30))
      style.setProperty('--el-color-primary-light-5', lighten(theme.primary, 50))
      style.setProperty('--el-color-primary-light-7', lighten(theme.primary, 70))
      style.setProperty('--el-color-primary-light-8', lighten(theme.primary, 80))
      style.setProperty('--el-color-primary-light-9', lighten(theme.primary, 90))
      style.setProperty('--el-color-primary-dark-2', darken(theme.primary, 20))
    }

    if (theme.success) {
      style.setProperty('--el-color-success', theme.success)
    }

    if (theme.warning) {
      style.setProperty('--el-color-warning', theme.warning)
    }

    if (theme.danger) {
      style.setProperty('--el-color-danger', theme.danger)
    }
  }

  // 保存主题到本地存储
  const saveTheme = (theme: ThemeColors) => {
    localStorage.setItem('app-theme', JSON.stringify(theme))
  }

  // 颜色变亮函数
  const lighten = (color: string, percent: number): string => {
    return adjustColor(color, percent)
  }

  // 颜色变暗函数
  const darken = (color: string, percent: number): string => {
    return adjustColor(color, -percent)
  }

  // 调整颜色明暗度
  const adjustColor = (color: string, percent: number): string => {
    // 移除 # 号
    let hex = color.replace('#', '')

    // 处理 3 位十六进制颜色
    if (hex.length === 3) {
      hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
    }

    // 解析 RGB 值
    const r = parseInt(hex.substring(0, 2), 16)
    const g = parseInt(hex.substring(2, 4), 16)
    const b = parseInt(hex.substring(4, 6), 16)

    // 计算调整后的 RGB 值
    const factor = percent / 100
    const newR = Math.round(Math.min(255, Math.max(0, r + (255 - r) * factor)))
    const newG = Math.round(Math.min(255, Math.max(0, g + (255 - g) * factor)))
    const newB = Math.round(Math.min(255, Math.max(0, b + (255 - b) * factor)))

    // 转换回十六进制
    const toHex = (num: number) => {
      const hex = num.toString(16)
      return hex.length === 1 ? '0' + hex : hex
    }

    return `#${toHex(newR)}${toHex(newG)}${toHex(newB)}`
  }

  // 主色调变化处理
  const handlePrimaryColorChange = (color: string | null) => {
    if (color) {
      primaryColor.value = color
      applyTheme({ primary: color })
      saveTheme({
        primary: color,
        success: successColor.value,
        warning: warningColor.value,
        danger: dangerColor.value,
      })
      nextTick(() => {
        hideDrawer() // 确保在 DOM 更新后再关闭抽屉
      })
    }
  }

  // 成功色变化处理
  const handleSuccessColorChange = (color: string | null) => {
    if (color) {
      successColor.value = color
      applyTheme({ success: color })
      saveTheme({
        primary: primaryColor.value,
        success: color,
        warning: warningColor.value,
        danger: dangerColor.value,
      })
      nextTick(() => {
        hideDrawer() // 确保在 DOM 更新后再关闭抽屉
      })
    }
  }

  // 警告色变化处理
  const handleWarningColorChange = (color: string | null) => {
    if (color) {
      warningColor.value = color
      applyTheme({ warning: color })
      saveTheme({
        primary: primaryColor.value,
        success: successColor.value,
        warning: color,
        danger: dangerColor.value,
      })
      nextTick(() => {
        hideDrawer() // 确保在 DOM 更新后再关闭抽屉
      })
    }
  }

  // 危险色变化处理
  const handleDangerColorChange = (color: string | null) => {
    if (color) {
      dangerColor.value = color
      applyTheme({ danger: color })
      saveTheme({
        primary: primaryColor.value,
        success: successColor.value,
        warning: warningColor.value,
        danger: color,
      })
      nextTick(() => {
        hideDrawer() // 确保在 DOM 更新后再关闭抽屉
      })
    }
  }

  // 重置主题
  const resetTheme = () => {
    primaryColor.value = defaultTheme.primary
    successColor.value = defaultTheme.success
    warningColor.value = defaultTheme.warning
    dangerColor.value = defaultTheme.danger

    applyTheme(defaultTheme)
    saveTheme(defaultTheme)
    nextTick(() => {
      hideDrawer() // 确保在 DOM 更新后再关闭抽屉
    })
  }

  // 组件挂载时初始化主题
  onMounted(() => {
    initTheme()
  })
</script>

<style scoped>
  .theme-switcher {
    display: inline-block;
  }

  .theme-button {
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
  }

  .theme-button::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      45deg,
      var(--el-color-primary),
      var(--el-color-success),
      var(--el-color-warning),
      var(--el-color-danger)
    );
    opacity: 0.2;
    transition: opacity 0.3s ease;
  }

  .theme-button:hover::before {
    opacity: 0.4;
  }

  .theme-content {
    padding: 10px 0;
  }

  .theme-item {
    height: 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
  }

  .reset-button {
    margin-top: 5px;
    color: var(--el-color-primary);
    padding: 0;
  }

  .theme-settings-title {
    font-size: 16px;
  }
</style>
